package com.xjh.serverinspect.util;

import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * shell命令执行结果转换工具类
 * </p>
 *
 * @author xujinghui
 * @since 2024-10-14
 */
public class ShellResultConvert {

    /**
     * 转换为表格信息
     *
     * @param str   待转换的字符串，以空格分隔，第一行解析为表格标题
     * @param title 标题
     * @return
     */
    public static ResultItem convert2table(String str, String title) {
        ResultItem resultItem = new ResultItem();
        resultItem.setTitle(title);
        resultItem.setContentType("table");
        if (str == null || str.isEmpty()) {
            resultItem.setMetaData(new String[]{"NULL"});
            resultItem.setRows(Collections.singletonList(new String[]{"NULL"}));
        } else {
            String[] rows = str.split("\n");
            resultItem.setMetaData(rows[0].replace("Mounted on", "MountedOn").split("\\s+"));

            ArrayList dataRows = new ArrayList();
            for (int i = 1; i < rows.length; i++) {
                dataRows.add(rows[i].split("\\s+"));
            }
            resultItem.setRows(dataRows);
        }

        return resultItem;
    }

    /**
     * 转换为表格信息
     *
     * @param str   [成功信息,错误信息]
     * @param title 标题
     * @return
     */
    public static ResultItem convert2table(String[] str, String title) {
        if (StringUtils.hasText(str[1])) {
            ResultItem resultItem = new ResultItem();
            resultItem.setTitle(title);
            resultItem.setContentType("table");
            resultItem.setMetaData(new String[]{"错误信息"});
            resultItem.setRows(Collections.singletonList(new String[]{String.format("<font color='#F56C6C'>%s</font>", str[1])}));
            return resultItem;
        } else {
            return convert2table(str[0], title);
        }
    }

    /**
     * 转换为表格信息
     *
     * @param str   待转换的字符串，以空格分隔
     * @param title 标题
     * @param meta  自定义表格标题
     * @return
     */
    public static ResultItem convert2table(String str, String title, String[] meta) {
        if (str == null || str.isEmpty())
            return null;

        ResultItem resultItem = new ResultItem();
        resultItem.setContentType("table");
        String[] rows = str.split("\n");
        resultItem.setMetaData(meta);
        resultItem.setRows(Arrays.stream(rows).map(item -> new String[]{item}).collect(Collectors.toList()));
        resultItem.setTitle(title);
        return resultItem;
    }

    /**
     * 转换为文本信息
     *
     * @param str   文本信息
     * @param title 标题
     * @return
     */
    public static ResultItem convert2text(String str, String title) {
        ResultItem resultItem = new ResultItem();
        resultItem.setContentType("text");
        resultItem.setTitle(title);
        resultItem.setText(str);
        return resultItem;
    }

    /**
     * 转换为错误信息
     *
     * @param str   错误信息
     * @param title 标题
     * @return
     */
    public static ResultItem convert2errorText(String str, String title) {
        ResultItem resultItem = new ResultItem();
        resultItem.setContentType("text");
        resultItem.setTitle(title);
        resultItem.setText(String.format("<font color='#F56C6C'>%s</font>", str));
        return resultItem;
    }

    /**
     * 转换为文本信息
     *
     * @param str   [成功信息,错误信息]
     * @param title 标题
     * @return
     */
    public static ResultItem convert2text(String[] str, String title) {
        ResultItem resultItem = new ResultItem();
        resultItem.setContentType("text");
        resultItem.setTitle(title);
        if (StringUtils.hasText(str[1])) {
            resultItem.setText(String.format("<font color='#F56C6C'>%s</font>", str[1]));
        } else {
            resultItem.setText(StringUtils.hasText(str[0]) ? str[0] : "<font color='#67C23A'>Success</font>");
        }
        return resultItem;
    }

    public static ResultItem convert2fileList(String[] str, String title) {
        if (StringUtils.hasText(str[1])) {
            ResultItem resultItem = new ResultItem();
            resultItem.setTitle(title);
            resultItem.setContentType("table");
            resultItem.setMetaData(new String[]{"错误信息"});
            resultItem.setRows(Collections.singletonList(new String[]{String.format("<font color='#F56C6C'>%s</font>", str[1])}));
            return resultItem;
        } else {
            return convert2fileList(str[0], title);
        }
    }

    public static ResultItem convert2fileList(String str, String title) {
        ResultItem resultItem = new ResultItem();
        resultItem.setTitle(title);
        resultItem.setContentType("table");
        if (str == null || str.isEmpty()) {
            resultItem.setMetaData(new String[]{"NULL"});
            resultItem.setRows(Collections.singletonList(new String[]{"NULL"}));
        } else {
            String[] rows = str.split("\n");
            resultItem.setMetaData(new String[]{"类型/权限", "硬链接数", "所有者", "组名", "大小", "修改时间", "文件名"});

            Pattern compile = Pattern.compile("([dlbcpsrwx\\-.]{10,})\\s+(\\d+)\\s+([a-zA-Z]+)\\s+([a-zA-Z]+)\\s+(\\d+)\\s+([a-zA-Z]{3}\\s+\\d{1,2}\\s+(\\d{2}:\\d{2}|\\d{4}))\\s+(.*)");
            ArrayList<String[]> dataRows = new ArrayList<>();
            for (int i = 1; i < rows.length; i++) {
                Matcher matcher = compile.matcher(rows[i]);
                if (matcher.find()) {
                    int count = matcher.groupCount();
                    List<String> groups = new ArrayList<>();
                    for (int j = 0; j < count; j++) {
                        groups.add(matcher.group(j + 1));
                    }
                    groups.remove(6);
                    dataRows.add(groups.toArray(new String[0]));
                }
            }
            resultItem.setRows(dataRows);
        }

        return resultItem;
    }

    public static ResultItem convert2pidList(String[] str, String title) {
        if (StringUtils.hasText(str[1])) {
            ResultItem resultItem = new ResultItem();
            resultItem.setTitle(title);
            resultItem.setContentType("table");
            resultItem.setMetaData(new String[]{"错误信息"});
            resultItem.setRows(Collections.singletonList(new String[]{String.format("<font color='#F56C6C'>%s</font>", str[1])}));
            return resultItem;
        } else {
            return convert2pidList(str[0], title);
        }
    }

    /**
     * 转换为进程列表信息（仅适用ps -ef命令）
     *
     * @param str   执行结果
     * @param title 标题
     * @return
     */
    public static ResultItem convert2pidList(String str, String title) {
        ResultItem resultItem = new ResultItem();
        resultItem.setTitle(title);
        resultItem.setContentType("table");
        if (str == null || str.isEmpty()) {
            resultItem.setMetaData(new String[]{"NULL"});
            resultItem.setRows(Collections.singletonList(new String[]{"NULL"}));
        } else {
            String[] rows = str.split("\n");
            String[] titleCols = new String[]{"UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"};
            resultItem.setMetaData(titleCols);

            ArrayList<String[]> dataRows = new ArrayList<>();
            for (int i = 0; i < rows.length; i++) {
                String[] split = rows[i].split("\\s+");
                if (split.length > titleCols.length) {
                    split[titleCols.length - 1] = String.join(" ", Arrays.copyOfRange(split, titleCols.length - 1, split.length));
                    split = Arrays.copyOfRange(split, 0, titleCols.length);
                }
                dataRows.add(split);
            }
            resultItem.setRows(dataRows);
        }

        return resultItem;
    }

}
